import {
  DeviceEventEmitter,
  EmitterSubscription,
  NativeModules,
  NativeEventEmitter
} from 'react-native';
import { REACT_NATIVE_SEI_DATA } from '../../constant/nativeEvent';
import { isIOS } from '../../constant';
import tracker from '../actionTracker';
import { requestError } from '../../constant/events';

const { RNSendEvent } = NativeModules;
const RNSendEventEmitter = new NativeEventEmitter(RNSendEvent);

enum EventType {
  Unknown,
  HaveProblem, // 1 - 有直播题需要进行互动，用户端根据eventData请求答题弹窗面板信息
  EndProblem // 2 - 直播题互动结束，用户端关闭答题弹窗
}

export interface EventData {
  liveProblemId: number;
  liveId: number;
}

export interface MsgData {
  eventType: EventType;
  eventData: EventData;
}

// 直播间答题开始
export const LIVE_PROBLEM_STAT_START = 'LIVE_PROBLEM_STAT_START';

// 直播间答题结束
export const LIVE_PROBLEM_STAT_END = 'LIVE_PROBLEM_STAT_END';

let pushMsgSubscription: EmitterSubscription;

const getData = (res: string): void => {
  try {
    const data = JSON.parse(res) as MsgData;
    const { eventType, eventData } = data;
    switch (eventType) {
      case EventType.HaveProblem:
        DeviceEventEmitter.emit(LIVE_PROBLEM_STAT_START, eventData);
        break;
      case EventType.EndProblem:
        DeviceEventEmitter.emit(LIVE_PROBLEM_STAT_END, eventData);
        break;
      default:
        break;
    }
  } catch (e) {
    tracker.reportAction(requestError, {
      path: 'json parse error sei data',
      reason: JSON.stringify({
        error: `${e}`,
        res
      })
    });
  }
};

export const startReceiveSEIMsg = (): void => {
  if (!isIOS) {
    pushMsgSubscription = DeviceEventEmitter.addListener(
      REACT_NATIVE_SEI_DATA,
      getData
    );
  } else {
    RNSendEventEmitter.addListener(REACT_NATIVE_SEI_DATA, getData);
  }
};

export const stopReceiveSEIMsg = (): void => {
  if (!isIOS) {
    if (pushMsgSubscription) {
      pushMsgSubscription.remove();
    }
  } else {
    RNSendEventEmitter.removeAllListeners();
  }
};
